<?php

namespace App\Jobs;

use App\Lib\Uploads\UploadHandler;
use App\Models\WxAttachment;
use App\Models\WxChat;
use App\Models\WxNotice;
use App\Wen\Utils\FileUtils;
use App\Wen\Utils\Settings;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Carbon;

class ChatExpireCleanJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {

        $rows = WxNotice::where('created_at', '<', Carbon::now()->subDays(60))->forceDelete();
        _logger_(__file__, __line__, 'ChatExpireCleanJob任务：共删除'.$rows.'条通知记录');

        global $__MINI_GLOBAL_PAYCODE_3__;
        if(!$__MINI_GLOBAL_PAYCODE_3__){
            return;
        }
        //
        $after_days = Settings::get('chat_expire_days', 90);
        $chats = WxChat::where('created_at', '<', Carbon::now()->subDays($after_days))->get();
        $clean_chats = 0;
        $clean_images = 0;
        if($chats){
            foreach ($chats as $chat){

                // 删除附件
                if($chat->chat_image){
                    $attachment_part = FileUtils::get_attachment_part_from_url($chat->chat_image);
                    if ($attachment_part) {
                        $the_attachment = WxAttachment::where([
                            ['domain', '=', $attachment_part['domain']],['path', '=', $attachment_part['path']]
                        ])->first();
                        if($the_attachment){
                            if(UploadHandler::del($the_attachment)){
                                $clean_images += 1;
                            }else{
                                _logger_(__file__, __line__, '清理图片失败');
                            }
                        }else{
                            _logger_(__file__, __line__, '不存在附件表的url地址');
                        }
                    }
                }

                $chat->forceDelete();
                $clean_chats += 1;

            }
        }
        _logger_(__file__, __line__, 'ChatExpireCleanJob任务：共删除'.$clean_chats.'条聊天记录，并清理掉 ' . $clean_images . '个附件');

    }
}
